import React from 'react';
import { Form, Input, Select, Textarea, Dialog } from 'tdesign-react';
import { FormProps } from 'tdesign-react';

const { FormItem } = Form;
const { Option } = Select;

export interface BaseFormField {
  name: string;
  label: string;
  type: 'input' | 'select' | 'textarea' | 'number';
  placeholder?: string;
  required?: boolean;
  options?: Array<{ value: string; label: string }>;
  rows?: number;
  initialData?: any;
}

export interface BaseFormProps {
  visible: boolean;
  onClose: () => void;
  onSubmit: (data: any) => void;
  initialData?: any;
  title: string;
  fields: BaseFormField[];
  width?: number;
}

export default function BaseForm({
  visible,
  onClose,
  onSubmit,
  initialData = {},
  title,
  fields,
  width = 600,
}: BaseFormProps) {
  const [form] = Form.useForm();

  const handleSubmit: FormProps['onSubmit'] = ({ validateResult, fields }) => {
    if (validateResult === true) {
      onSubmit(fields);
    }
  };

  const renderField = (field: BaseFormField) => {
    const commonProps = {
      placeholder: field.placeholder,
      initialData: field.initialData || initialData?.[field.name],
    };

    switch (field.type) {
      case 'input':
        return <Input {...commonProps} />;
      case 'select':
        return (
          <Select {...commonProps}>
            {field.options?.map((option) => (
              <Option key={option.value} value={option.value} label={option.label}>
                {option.label}
              </Option>
            ))}
          </Select>
        );
      case 'textarea':
        return <Textarea {...commonProps} rows={field.rows || 3} />;
      case 'number':
        return <Input {...commonProps} type="number" />;
      default:
        return <Input {...commonProps} />;
    }
  };

  return (
    <Dialog
      closeOnOverlayClick={false}
      header={title}
      visible={visible}
      onClose={onClose}
      onConfirm={() => form.submit()}
      destroyOnClose
      width={width}
    >
      <Form
        form={form}
        initialData={initialData}
        layout="vertical"
        onSubmit={handleSubmit}
      >
        {fields.map((field) => (
          <FormItem
            key={field.name}
            label={field.label}
            name={field.name}
            rules={field.required ? [{ required: true, message: `请输入${field.label}` }] : []}
          >
            {renderField(field)}
          </FormItem>
        ))}
      </Form>
    </Dialog>
  );
}
